//
//  NetworkManager.swift
//  SouWeiLaiSwift
//
//  Created by yxl on 2022/4/13.
//

import UIKit
import Moya
import Alamofire
import SwiftyJSON

class NetworkManager: NSObject {
    
    ///成功数据的回调
    typealias successCallback = ((JSON) -> (Void))
    ///失败的回调
    typealias failedCallback = ((String) -> (Void))
    ///网络错误的回调
    typealias errorCallback = (() -> (Void))

     /// 基于Alamofire,网络是否连接，这个方法不建议放到这个类中,可以放在全局的工具类中判断网络链接情况
     /// 用get方法是因为这样才会在获取isNetworkConnect时实时判断网络链接请求，如有更好的方法可以fork
     static var isNetworkConnect: Bool {
         get{
             let network = NetworkReachabilityManager()
             return network?.isReachable ?? true //无返回就默认网络已连接
         }
     }

    ///网络请求的设置
    static let requestClosure = { (endpoint: Endpoint, done: MoyaProvider.RequestResultClosure) in
        do {
            var request = try endpoint.urlRequest()
            //设置请求时长
            request.timeoutInterval = 30
            // 打印请求参数
            if let requestData = request.httpBody {
                print("\(request.url!)"+"\n"+"\(request.httpMethod ?? "")"+"发送参数"+"\(String(data: request.httpBody!, encoding: String.Encoding.utf8) ?? "")")
            }else{
                print("\(request.url!)"+"\(String(describing: request.httpMethod))")
            }
            done(.success(request))
        } catch {
            done(.failure(MoyaError.underlying(error, nil)))
        }
    }

    /// NetworkActivityPlugin插件用来监听网络请求，界面上做相应的展示
    ///但这里我没怎么用这个。。。 loading的逻辑直接放在网络处理里面了
    static let networkPlugin = NetworkActivityPlugin.init { (changeType, targetType) in
        print("networkPlugin \(changeType)")
        //targetType 是当前请求的基本信息
        switch(changeType){
        case .began:
            print("开始请求网络")
            
        case .ended:
            print("结束")
        }
    }

    /*   设置ssl
    let policies: [String: ServerTrustPolicy] = [
        "example.com": .pinPublicKeys(
            publicKeys: ServerTrustPolicy.publicKeysInBundle(),
            validateCertificateChain: true,
            validateHost: true
        )
    ]
    */

    // 用Moya默认的Manager还是Alamofire的Manager看实际需求。HTTPS就要手动实现Manager了
    //private public func defaultAlamofireManager() -> Manager {
    //
    //    let configuration = URLSessionConfiguration.default
    //
    //    configuration.httpAdditionalHeaders = Alamofire.SessionManager.defaultHTTPHeaders
    //
    //    let policies: [String: ServerTrustPolicy] = [
    //        "ap.grtstar.cn": .disableEvaluation
    //    ]
    //    let manager = Alamofire.SessionManager(configuration: configuration,serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies))
    //
    //    manager.startRequestsImmediately = false
    //
    //    return manager
    //}
}
